package com.shine.app.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.shine.app.AppManager;
import com.shine.app.BaseActivity;
import com.shine.app.R;
import com.shine.app.bean.UserBean;
import com.shine.app.bean.UserInfoBean;
import com.shine.app.bean.request.CredentialBean;
import com.shine.app.bean.responses.AuthenticateUserResponse;
import com.shine.app.commons.StringUtils;
import com.shine.app.commons.UIHelper;
import com.shine.app.inject.InjectView;
import com.shine.app.inject.Injector;

public class LoginActivity extends BaseActivity implements OnClickListener {

	@InjectView(R.id.username)
	private EditText usernameEditText;
	@InjectView(R.id.password)
	private EditText passwordEditText;
	@InjectView(R.id.login)
	private Button loginButton;
	@InjectView(R.id.signup)
	private Button signupButton;
	@InjectView(R.id.forgot)
	private ImageView forgoImageView;
	@InjectView(R.id.head_back)
	private ImageView head_backImageView;
	@InjectView(R.id.head_name)
	private TextView head_nameTextView;
	@InjectView(R.id.progressBar)
	private ProgressBar progressBar;
	

	Handler handler = new Handler() {
		public void handleMessage(Message message) {
			if (message.what == 1) {
				UserInfoBean userInfoBean = (UserInfoBean) message.obj;
				UserBean user = userInfoBean.getUser();
				if (user != null) {
					user.setHasPassword(true);
					UIHelper.toastDialog(LoginActivity.this,
							R.string.loginsuccess, R.string.msg_yes);
					AppManager.getAppManager().finishActivity();
					appContext.saveLoginInfo(userInfoBean);
					overridePendingTransition(R.anim.anim,
							R.anim.slide_out_down);
				}
			} else if (message.what == 0) {
				appContext.cleanLoginInfo();
				UIHelper.toastDialog(LoginActivity.this,
						R.string.msg_login_fail, R.string.msg_yes);
			} else if (message.what == -1) {
				Exception exception = (Exception) message.obj;
				UIHelper.toastDialogs(LoginActivity.this,
						exception.getMessage(), R.string.msg_yes);
			}
			resetViewStatus(true);
		}
	};

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		Injector.get(this).inject();

		init();
		clickListener();
	}

	private void clickListener() {
		loginButton.setOnClickListener(this);
		signupButton.setOnClickListener(this);
		forgoImageView.setOnClickListener(this);
		head_backImageView.setOnClickListener(this);

	}

	private void init() {
		progressBar.setVisibility(View.GONE);
		UserInfoBean user = appContext.getLoginInfo();
		if (user == null) {
			return;
		}
		String email = user.getUser().getEmail();
		if (!StringUtils.isEmpty(email)) {
			usernameEditText.setText(email);
			usernameEditText.selectAll();
		}
		usernameEditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				passwordEditText.getText().clear();
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
				passwordEditText.getText().clear();
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
		UserInfoBean user = appContext.getLoginInfo();
		if (user == null) {
			return;
		}
		String email = user.getUser().getEmail();
		if (!StringUtils.isEmpty(email)) {
			usernameEditText.setText(email);
			usernameEditText.selectAll();
		}
	}

	private void login(final CredentialBean credentialBean) {
		resetViewStatus(false);
		new Thread() {
			public void run() {
				Message message = new Message();
				try {
					AuthenticateUserResponse response = appContext
							.authenticateUser(credentialBean);
					if (response == null || response.isHasError()) {
						message.what = 0;
						message.obj = response;
					} else {
						message.what = 1;
						UserInfoBean userInfoBean = new UserInfoBean();
						UserBean userBean = response.getData();
						userBean.setEmail(credentialBean.getEmail());
						userInfoBean.setPassword(credentialBean.getPassword());
						userInfoBean.setUser(userBean);
						message.obj = userInfoBean;
					}
				} catch (Exception e) {
					e.printStackTrace();
					message.what = -1;
					message.obj = e;
				}
				handler.sendMessage(message);
			}
		}.start();
	}

	@Override
	public void onClick(View v) {
		Intent intent = new Intent();
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		switch (v.getId()) {

		case R.id.head_back:
			AppManager.getAppManager().finishActivity();
			overridePendingTransition(R.anim.anim, R.anim.slide_out_down);
			break;

		case R.id.login:
			loginButton.startAnimation(buttonAnimations);
			inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
			String email = getEditTextValues(usernameEditText);
			String password = getEditTextValues(passwordEditText);
			if (!validation(email, password)) {
				return;
			}
			CredentialBean credentialBean = new CredentialBean(email, password);
			login(credentialBean);
			break;

		case R.id.signup:
			signupButton.startAnimation(buttonAnimations);
			intent.setClass(this, RegisterActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		case R.id.forgot:
			forgoImageView.startAnimation(buttonAnimations);
			intent.setClass(this, ForgotPasswordActivity.class);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_in_up, R.anim.anim);
			break;

		default:
			break;
		}
	}

	private boolean validation(String email, String password) {
		if (StringUtils.isEmpty(email)) {
			UIHelper.toastDialog(this, R.string.msg_email_field_empty,
					R.string.msg_yes);
			return false;
		}
		if (!StringUtils.isEmail(email)) {
			UIHelper.toastDialog(this, R.string.msg_invalid_email_format,
					R.string.msg_yes);
			return false;
		}
		if (StringUtils.isEmpty(password)) {
			UIHelper.toastDialog(this, R.string.msg_password_field_empty,
					R.string.msg_yes);
			return false;
		}
		return true;
	}

	private void resetViewStatus(boolean flag) {
		if (flag) {
			progressBar.setVisibility(View.GONE);
		} else {
			progressBar.setVisibility(View.VISIBLE);
		}
		loginButton.setClickable(flag);
		signupButton.setClickable(flag);
		forgoImageView.setClickable(flag);
		head_backImageView.setClickable(flag);
		usernameEditText.setEnabled(flag);
		passwordEditText.setEnabled(flag);
	}
}
